#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QLibraryInfo>
#include <QTranslator>
#include <QDBusConnection>
#include <QTextStream>
#include <QMessageBox>
#include "core/controller.h"
#include "singleapplication.h"
#include <gst/gst.h>
#include "widgets/statusbar.h"
#include "core/flameshotdbusadapter.h"
#include "utils/screencapsaver.h"
#include "core/capturerequest.h"
#include "utils/cli/commandlineparser.h"
#include "utils/cli/commandargument.h"
#include "utils/cli/commandoption.h"
#include "../screencapsdk/kysdk-qtwidgets/kmessagebox.h"
#include "../screencapsdk/kysdk-log/log.hpp"

bool checkSystemVersion() {
    qDebug()<<"检查系统版本";
    QFile file("/etc/os-release");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"无法读取系统版本信息";
        return false;
    }
    QTextStream in(&file);
    QString line;
    QString kylinReleaseId = "";
    while (in.readLineInto(&line)) {
       if (line.startsWith("KYLIN_RELEASE_ID=")) {
           kylinReleaseId = line.section('=', 1).trimmed().replace("\"", "");
           break;
       }
    }
    if (kylinReleaseId.isEmpty()) {
        qDebug()<<"KYLIN_RELEASE_ID字段不存在或为空";
        return false;
    }
    if(kylinReleaseId == "V11"){
        qDebug()<<"KYLIN_RELEASE_ID="<<kylinReleaseId;
        return true;
    }
    bool isConvertOk;
    int releaseId = kylinReleaseId.toInt(&isConvertOk);
    if (!isConvertOk) {
        qDebug()<<"kylinReleaseId值无效";
        return false;
    }

    if (releaseId < 2203) {
        qDebug()<<"系统版本过低";
        return false;
    }

    qDebug()<<"KYLIN_RELEASE_ID="<<kylinReleaseId;
    return true;
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(kdk::kabase::Log::logOutput);
    //分辨率适配
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

    gst_init (&argc, &argv);
    //主题框架设置

    qApp->setApplicationVersion(static_cast<QString>(APP_VERSION));
    if (qgetenv("QT_QPA_PLATFORMTHEME") != "ukui")
        qputenv("QT_QPA_PLATFORMTHEME", "ukui");

    if (argc == 1) {
        SingleApplication app(argc, argv);
        app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
        app.setApplicationName(QObject::tr("kylin-screencap"));

        //翻译
        QTranslator app_trans;
        QTranslator qt_trans;
        QString locale = QLocale::system().name();
        QString trans_path;
        if (QDir("/usr/share/kylin-screencap/translations").exists()) {
            trans_path = "/usr/share/kylin-screencap/translations";
        } else {
            trans_path = qApp->applicationDirPath() + "/translations";
        }
        QString qt_trans_path;
        qt_trans_path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); // /usr/share/qt5/translations
        if (!qt_trans.load("qt_" + locale + ".qm", qt_trans_path)) {
            qDebug() << "Load translation file："
                     << "qt_" + locale + ".qm from" << qt_trans_path << "failed!";
        } else {
            app.installTranslator(&qt_trans);
        }
        QTranslator sdk_trans;
        if (sdk_trans.load(":/translations/gui_" + locale + ".qm")) {
            app.installTranslator(&sdk_trans);
        }
        if (!app_trans.load("kylin-screencap_" + locale + ".qm", trans_path)) {
            qDebug() << "Load translation file："
                     << "kylin-screencap_" + locale + ".qm from" << trans_path << "failed!";
        } else {
            app.installTranslator(&app_trans);
        }

//        if (!checkSystemVersion()) {
//            KMessageBox kmsg;
//            kmsg.setIcon(KMessageBox::Warning);
//            kmsg.setText(QString((QObject::tr("The current system version does not support kylin-screencap apps, you can update the system to V10 SP1 2203 or later and use it normally."))));
//            kmsg.addButton(QObject::tr("OK"), KMessageBox::YesRole);
//            kmsg.exec();
//            return 1;
//        }

        app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
        app.setApplicationName(QObject::tr("kylin-screencap"));
        app.setOrganizationName(QStringLiteral("Dharkael"));
        app.setProperty("useFileDialog", false);
        app.setWindowIcon(QIcon::fromTheme("kylin-screencap"));

        auto c = Controller::getInstance();

        new FlameshotDBusAdapter(c);
        QDBusConnection dbus = QDBusConnection::sessionBus();
        if (!dbus.isConnected()) {
            ScreencapSaver().sendMessage(
                QObject::tr("Unable to connect via DBus"));
        }
        dbus.registerObject(QStringLiteral("/"), c);
        dbus.registerService(QStringLiteral("org.dharkael.kylinscreencap"));

        //不使用默认注销流程
        QGuiApplication::setFallbackSessionManagementEnabled(false);
        QObject::connect(&app, &SingleApplication::commitDataRequest, c, &Controller::commitData);

        return app.exec();
    }

    QCoreApplication app(argc, argv);
    app.setApplicationName(QObject::tr("Kylin-Screencap"));
    app.setOrganizationName(QStringLiteral("Dharkael"));
    app.setApplicationVersion(qApp->applicationVersion());

    //命令行参数 CLI parsing
    CommandLineParser parser;
    parser.setDescription(
        QStringLiteral("Powerful yet simple to use screenshot software."));
    parser.setGeneralErrorMessage(QStringLiteral("See 'kylin-screencap --help'."));
    // Arguments
    CommandArgument fullArgument(QStringLiteral("full"),
                                 QStringLiteral("Capture the entire desktop."));
    CommandArgument settingArgument(QStringLiteral("setting"),
                                     QStringLiteral("Open the capture save setting."));
    CommandArgument guiArgument(QStringLiteral("gui"),
                                QStringLiteral("Start a manual capture in GUI mode."));
    CommandArgument osManagerArgument(QStringLiteral("osmanager"),
                                QStringLiteral("Start a manual capture in GUI mode from kylin-os-manager."));
    CommandArgument screenArgument(QStringLiteral("screen"),
                                   QStringLiteral("Capture a single screen."));

    // Options
    CommandOption showHelpOption(
        {"s", "showhelp"},
        QStringLiteral("Show the help message in the capture mode"),
        QStringLiteral("bool"));

    //check
    const QString booleanErr = QStringLiteral(
        "Invalid value, it must be defined as 'true' or 'false'");
    auto booleanChecker = [](const QString &value) -> bool {
                              return value == QLatin1String("true") || value == QLatin1String(
                                  "false");
                          };

    showHelpOption.addChecker(booleanChecker, booleanErr);

    // Relationships
    parser.AddArgument(guiArgument);
    parser.AddArgument(osManagerArgument);
    parser.AddArgument(screenArgument);
    parser.AddArgument(fullArgument);
    parser.AddArgument(settingArgument);

    //help
    auto helpOption = parser.addHelpOption();
    auto versionOption = parser.addVersionOption();

    // Parse
    if (!parser.parse(app.arguments())) {
        goto finish;
    }

    // PROCESS DATA
    // --------------
    if (parser.isSet(helpOption) || parser.isSet(versionOption)) {
    }

    else if (parser.isSet(settingArgument)) { // SETTING
        qDebug()<<"main - 命令行的处理 SETTING";
        QDBusMessage m
            = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.kylinscreencap"),
                                             QStringLiteral("/"), QLatin1String(
                                                 ""), QStringLiteral("openSetting"));
        QDBusConnection sessionBus = QDBusConnection::sessionBus();
        if (!sessionBus.isConnected()) {
            ScreencapSaver().sendMessage(
                QObject::tr("Unable to connect via DBus"));
        }
        sessionBus.call(m);
    }

    else if (parser.isSet(guiArgument)) { // GUI
        qDebug()<<"main - 命令行的处理 GUI";
        CaptureRequest req(CaptureRequest::GRAPHICAL_MODE);
        uint id = req.id();
        QDBusMessage m
            = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.kylinscreencap"),
                                             QStringLiteral("/"), QLatin1String(
                                                 ""), QStringLiteral("graphicCapture"));
        QDBusConnection sessionBus = QDBusConnection::sessionBus();
        m << id;
        sessionBus.call(m);
    }

    else if (parser.isSet(osManagerArgument)) { // kylin-os-manager
        qDebug()<<"main - 命令行的处理 kylin-os-manager";
        CaptureRequest req(CaptureRequest::GRAPHICAL_MODE);
        uint id = req.id();
        QDBusMessage m
            = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.kylinscreencap"),
                                             QStringLiteral("/"), QLatin1String(
                                                 ""), QStringLiteral("osManagerCapture"));
        QDBusConnection sessionBus = QDBusConnection::sessionBus();
        m << id;
        sessionBus.call(m);
    }

    else if (parser.isSet(fullArgument)) { // FULL
        qDebug()<<"main - 命令行的处理 FULL";
        CaptureRequest req(CaptureRequest::FULLSCREEN_MODE);
        uint id = req.id();
        QDBusMessage m
            = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.kylinscreencap"),
                                             QStringLiteral("/"), QLatin1String(
                                                 ""), QStringLiteral("fullScreen"));
        QDBusConnection sessionBus = QDBusConnection::sessionBus();
        m << id;
        sessionBus.call(m);
    }

    else if (parser.isSet(screenArgument)) { // SCREEN
        qDebug()<<"main - 命令行的处理 SCREEN";
        int number = 1;
        CaptureRequest req(CaptureRequest::SCREEN_MODE);
        uint id = req.id();
        QDBusMessage m
            = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.kylinscreencap"),
                                             QStringLiteral("/"), QLatin1String(
                                                 ""), QStringLiteral("captureScreen"));
        QDBusConnection sessionBus = QDBusConnection::sessionBus();
        m << number << id;
        sessionBus.call(m);
    }

finish:
    return 0;
}
